package com.lagou.rocketmq.listener;

import com.alibaba.fastjson.JSON;
import com.lagou.rocketmq.mapper.GoodsMapper;
import com.lagou.rocketmq.mapper.OrderMapper;
import com.lagou.rocketmq.pojo.Goods;
import com.lagou.rocketmq.pojo.GoodsExample;
import com.lagou.rocketmq.pojo.Order;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Component
@RocketMQMessageListener(topic = "orderList", consumerGroup = "consumer")
public class OrderListener implements RocketMQListener<String> {

    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(String message) {
        String[] infos = message.split("-");
        System.out.println("商品：" + infos[0] + " 购买人id：" + infos[1]);

        //减库存
        GoodsExample example = new GoodsExample();
        example.createCriteria().andNameEqualTo(infos[0]);
        List<Goods> goodList = goodsMapper.selectByExample(example);
        Goods goods = goodList.get(0);
        goods.setTotal(goods.getTotal() - 1);
        goodsMapper.updateByPrimaryKey(goods);

        //创建订单
        Order order = new Order();
        order.setOrderid(UUID.randomUUID().toString().replace("-",""));
        order.setUserid(Integer.parseInt(infos[1]));
        order.setStatus(0);
        order.setGoodsid(goods.getId());
        order.setCreateDate(new Date());
        orderMapper.insertSelective(order);

        /*RedisDelayedQueue redisDelayedQueue = new RedisDelayedQueue();
        redisDelayedQueue.addQueue(order,10, TimeUnit.SECONDS);

        //监听延迟队列
        RedisDelayedQueue.TaskEventListener<Order> taskEventListener = new RedisDelayedQueue.TaskEventListener<Order>() {
            @Override
            public void invoke(Order orderInfo) {
                OrderExample orderExample = new OrderExample();
                orderExample.createCriteria().andOrderidEqualTo(orderInfo.getOrderid()).andStatusEqualTo(0);
                List<Order> orders = orderMapper.selectByExample(orderExample);
                if(orders != null && orders.size()>0){
                    orderMapper.updateOrderStatus(orderInfo.getOrderid(),1);
                }
            }
        };
        redisDelayedQueue.getQueue(Order.class, taskEventListener);*/


        /*Message orderMessage = new Message();
        orderMessage.setBody(JSON.toJSONString(order).getBytes());
        orderMessage.setDelayTimeLevel(3);
        rocketMQTemplate.convertAndSend("pay_timeout",orderMessage);*/
    }
}
